const bcrypt = require("bcrypt");
const { getUserInfo } = require("../service/userService");
const {
  userFormateError,
  useAlreadyExited,
  userRegisterError,
  userDoesNotExist,
  userLoginError,
  invalidPassword,
} = require("../constant/error");
const userValidator = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;
  if (!user_name || !password) {
    // ctx.status = 400
    // ctx.body = {
    //     code: 400,
    //     message: '用户名或者密码为空',
    //     result: ''
    // }
    ctx.app.emit("error", userFormateError, ctx);
    return;
  }
  await next();
};
const verifyUser = async (ctx, next) => {
  const { user_name } = ctx.request.body;
  // if(await getUserInfo(user_name)){
  //     ctx.app.emit('error', useAlreadyExited, ctx)
  //     return
  // }
  try {
    const res = await getUserInfo({ user_name });
    if (res) {
      ctx.app.emit("error", useAlreadyExited, ctx);
      return;
    }
  } catch (err) {
    console.error(err);
    ctx.app.emit("error", userRegisterError, ctx);
    return;
  }
  await next();
};
const cryptPassword = async (ctx, next) => {
  const { password } = ctx.request.body;
  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(password, salt);
  ctx.request.body.password = hash;
  await next();
};
const verifyLogin = async (ctx, next) => {
  // 1、判断用户存在与否
  const { user_name, password } = ctx.request.body;
  try {
    const res = await getUserInfo({ user_name });
    if (!res) {
      ctx.app.emit("error", userDoesNotExist, ctx);
      return;
    }
    // 2. 密码匹配
    if (!bcrypt.compareSync(password, res.password)) {
      ctx.app.emit("error", invalidPassword, ctx);
      return;
    }
  } catch {
    console.error(err);
    ctx.app.emit("error", userLoginError, ctx);
    return;
  }
  await next();
};
module.exports = {
  userValidator,
  verifyUser,
  cryptPassword,
  verifyLogin,
};
